package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.dao.AdminMapper;
import cn.ncu.wechat.dao.OrdersMapper;
import cn.ncu.wechat.dao.VerificationMapper;
import cn.ncu.wechat.model.*;
import cn.ncu.wechat.service.VerificationService;
import cn.ncu.wechat.util.Result;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@Service
public class VerificationServiceImpl extends ServiceImpl<VerificationMapper, Verification>
        implements VerificationService {
    @Value("${cn.ncu.key}")
    private String key;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private VerificationMapper verificationMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Transactional
    @Override
    public Result<?> addVerification(VerificationRequest request,String token) {
        try{
            if (verificationMapper.selectOne(new QueryWrapper<Verification>().eq("verification_code",request.getVerificationCode()))!=null) return Result.fail(401,"请勿重复使用核验码");
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",2);
            queryWrapper.eq("order_no",request.getOrderNo());
            if (ordersMapper.selectOne(queryWrapper)==null) return Result.fail(401,request.getOrderNo()+"：不可核销状态，具体原因请联系管理员");
            Algorithm algorithm = Algorithm.HMAC256(key);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            System.out.println("token="+token);
            DecodedJWT decodedJWT = jwtVerifier.verify(token.substring(7));
            Long adminId = decodedJWT.getClaim("id").asLong();
            String operator = adminMapper.selectOne(new QueryWrapper<Admin>().eq("id",adminId)).getName();
            Date now = new Date(System.currentTimeMillis());
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("verification_code",request.getVerificationCode());
            updateWrapper.set("verification_time",now);
            updateWrapper.set("update_time",now);
            updateWrapper.set("status",3);
            updateWrapper.eq("order_no",request.getOrderNo());
            Verification verification = new Verification();
            verification.setOrderNo(request.getOrderNo());
            verification.setStoreId(request.getStoreId());
            verification.setVerificationCode(request.getVerificationCode());
            verification.setOperator(operator);
            if (!request.getRemark().isBlank())  verification.setRemark(request.getRemark());
            verificationMapper.insert(verification);
            ordersMapper.update(updateWrapper);
            Map<String,String > result = ordersMapper.getStoreNameAndProductNameByOrder(request.getStoreId(), request.getOrderNo());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("operator",operator);
            jsonObject.put("verificationTime",now);
            jsonObject.put("orderNo",request.getOrderNo());
            jsonObject.put("storeName",result.get("storeName"));
            jsonObject.put("productName",result.get("productName"));
            return Result.success(jsonObject,"核销成功");
        } catch (Exception e){
            return Result.error(500,"服务器错误"+e);
        }
    }

    public Result<?> checkVerification(String verificationCode){
        try{
            Map<String,Object> resultmap = verificationMapper.check(verificationCode);
            JSONObject jsonObject = new JSONObject();
            if (resultmap==null){
                jsonObject.put("valid",false);
                return Result.success(jsonObject);
            }
            else {
                resultmap.put("valid",true);
                return Result.success(resultmap);
            }
        } catch (Exception e){
            return Result.error(500,"服务器错误"+e);
        }
    }

    @Override
    public Result<?> sumByDate(String startDate, String endDate, Long storeId) {
        try {
            VerificationCount verificationCount = new VerificationCount();
            ArrayList<DailyStat> dailyStat = verificationMapper.getDailyStat(startDate,endDate);
            Overview overview = verificationMapper.getOverView(startDate,endDate);
            ArrayList<StoreStat> storeStats = verificationMapper.getStoreStats(startDate,endDate,storeId);

            verificationCount.setOverview(overview);
            verificationCount.setStoreStats(storeStats);
            verificationCount.setDailyStats(dailyStat);
            return Result.success(verificationCount);
        } catch (Exception e){
            return Result.error(500,"服务器错误"+e);
        }
    }
}
